package com.luxsoft.siipap.em.replica.importadores.cxc;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;

import com.luxsoft.siipap.em.replica.importadores.dbf.DBFRowHandler;
import com.luxsoft.siipap.em.service.EMServiceLocator;
import com.luxsoft.siipap.model.CantidadMonetaria;
import com.luxsoft.siipap.model.Direccion;
import com.luxsoft.siipap.model.core.Cliente;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.util.DBUtils;

/**
 * Permite actualizar algunas propiedades del catalogo de clientes
 * a partir del archivo DBF
 * 
 * @author Ruben Cancino Ramos
 *
 */
public class ActualizadorDeClientesDBF implements DBFRowHandler{
	
	
	
	private Logger logger=Logger.getLogger(getClass());
	
	
	
	
	public ActualizadorDeClientesDBF(){
		
	}	
	
	public void actualizar(String clave){
		List<Cliente> clientes=ServiceLocator2
			.getHibernateTemplate().find("from Cliente c left join fetch c.credito where c.clave=?",clave);
		setTotal(clientes.size());
		for(Cliente target:clientes){
			logger.info("Actualizando cliente: "+target);
			try {
				Cliente source=findClienteEnDBF(target.getClave());
				copyProperties(target, source);
				ServiceLocator2.getUniversalDao().save(target);
			} catch (Exception e) {
				logger.error(ExceptionUtils.getRootCause(e),e);
				continue;
			}finally{
				updateCurrent();
			}
		}
	}
	
	public void actualizar(){
		List<Cliente> clientes=ServiceLocator2.getHibernateTemplate().find("from Cliente c left join fetch c.credito where c.credito is not null");
		setTotal(clientes.size());
		for(Cliente target:clientes){
			logger.info("Actualizando cliente: "+target);
			try {
				Cliente source=findClienteEnDBF(target.getClave());
				copyProperties(target, source);
				ServiceLocator2.getUniversalDao().save(target);
			} catch (Exception e) {
				logger.error(ExceptionUtils.getRootCause(e),e);
				continue;
			}finally{
				updateCurrent();
			}
		}
	}
	
	private Cliente findClienteEnDBF(String clave){
		String sql="SELECT * FROM CLIENTES X WHERE X.CLICLAVE=?";
		Object params[]=new String[]{clave};
		List res=EMServiceLocator.instance().getSiipapDBFOdbcTemplate().query(sql, params, new ClienteMapper());
		Assert.notEmpty(res,"No localizo en DBF el cliente: "+clave);
		return (Cliente)res.get(0);
	}
	
	private void copyProperties(Cliente target,Cliente source){
		target.setNombre(source.getNombre());
		target.setDireccionFiscal(source.getDireccionFiscal());
		target.setCuentaContable(source.getCuentaContable());
		target.setPermitirCheque(source.isPermitirCheque());
		
		
		target.getCredito().setDiarevision(source.getCredito().getDiarevision());
		target.getCredito().setDiacobro(source.getCredito().getDiacobro());
		target.getCredito().setVencimientoFactura(source.getCredito().isVencimientoFactura());
		target.getCredito().setLinea(source.getCredito().getLinea());
		target.getCredito().setPlazo(source.getCredito().getPlazo());
		target.getCredito().setOperador(source.getCredito().getOperador());
		
	}
		
	public void processRow(Map<String, Object> row) throws Exception {
		System.out.println(row);
		
	}	
	
	
	private int current;
	
	private int total;
	
	public void setProgress(int progress){
		//System.out.println("Progress: "+progress);
	}
	
	protected void updateCurrent(){
		current++;		
		if(total!=0){
			int progress=current*100/this.total;
			System.out.println("Progress:"+progress);
			setProgress(progress);
		}
	}
	
	public void setTotal(int total) {
		this.total = total;
		logger.info("Total de ventas a importar:"+total);
	}
	
	private class ClienteMapper implements RowMapper{

		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			//Data: {CLICLAVE=I110080, CLICLAVORI=I110080
			//, CLINOMBRE=INTELLINGENT PRINT VICENCIO S.A. DE C.V., CLICALLE=ORIENTE 249*A N0.99, CLICOLON=AGRICOLA ORIENTAL, CLIDELEG=IZTACALCO, CLIPOSTAL=08500, CLITEL1=57015358, CLIFAX=null, CLIRFC=IPV 0807074Q4, CLIREVISIO=1.0, CLIPAGO=1.0, CLICOBRADO=1.0, CLIAGENTE=1.0, CLILIMITE=1.0, CLIFECREAL=2008-10-13, CLIFECSIAL=2008-10-13, CLISUSPEN=null, CLICOMSUS=null, CLIOBSGRAL=AUTORIZO EL LIC. RAFAEL  $100,000.00, CLICUENTA=106-I111-000, CLICLASIFI=30.0, CLIFECLASI=2009-02-25, CLIOBSCLAS=null, CLIGERGRAL=null, CLIGERCOMP=null, CLICEDULA=N, CLIPLAZO=20.0, CLITIPVTO=F, CLIPAGARE=N, CLIOPEDEPU=null, CLIFECDEPU=null, CLIBACOCO=null, CLIBACOVE=null, CLIESLIDER=N, CLILIDER=null, CLIESTADO=A, CLICOMEDO=null, CLICOTIZA=S, CLICOMCOT=null, CLIPEDIDO=S, CLICOMPED=null, CLIFACTUR=S, CLICOMFAC=null, CLIPORCDES=null, CLIPORCDE2=null, CLITIPO=CON, CLICTRLGRA=I, CLIFORPAGO=EPC, CLIMOIMPNI=N, CLIABOGADO=null, CLIFEASIAB=null, CLIOPERADO=1.0, CLIUSUAR=10.0, CLIBACOVC=null, CLIFATENCL=null, CLIFATENMO=2009-04-29, CLIAATENCL=null, CLIAATENMO=null, CLIEMAIL=null, CLITELANT=57015358, CLIFAXANT=null, CLIGIROEMP=null, CLIMANUAL=null, CLILIPRCRE=null, CLIALPRCRE=null, CLILIPRCON=null, CLIALPRCON=null, CLIEQUIORG=null, CLIHORAREG=null, CLIACCES=null, CLIVERSION=null}
			
			Cliente c=new Cliente();
			c.setClave(rs.getString("CLICLAVE"));
			c.setNombre(rs.getString("CLINOMBRE"));
			Direccion direccion=new Direccion();
			direccion.setCalle(rs.getString("CLICALLE"));
			direccion.setColonia(rs.getString("CLICOLON"));
			direccion.setMunicipio(rs.getString("CLIDELEG"));
			direccion.setCp(rs.getString("CLIPOSTAL"));
			c.setDireccionFiscal(direccion);
			c.setCuentaContable(rs.getString("CLICUENTA"));
			c.setPermitirCheque(rs.getString("CLIFORPAGO").equals("CEH"));
			
			c.habilitarCredito();
			c.getCredito().setDiarevision(rs.getInt("CLIREVISIO"));
			c.getCredito().setDiacobro(rs.getInt("CLIPAGO"));
			c.getCredito().setVencimientoFactura(rs.getString("CLITIPVTO").equals("F"));
			BigDecimal linea=rs.getBigDecimal("CLILIMITE");
			if(linea==null)linea=BigDecimal.ZERO;
			c.getCredito().setLinea(CantidadMonetaria.pesos(linea.doubleValue()));
			c.getCredito().setPlazo(rs.getInt("CLIPLAZO"));
			c.getCredito().setOperador(rs.getInt("CLIOPERADO"));
			
			//,""
			//,"CLIESTADO"
			//,"CLITIPO"
			//,""
			//,""
			return c;
		}
		
	}
	
	public static void main(String[] args) {
		DBUtils.whereWeAre();
		new ActualizadorDeClientesDBF()		
		//.actualizar("P010389");
		.actualizar();
	}
}
